package vertx;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.mysqlclient.MySQLConnectOptions;
import io.vertx.mysqlclient.MySQLPool;
import io.vertx.sqlclient.PoolOptions;
import io.vertx.sqlclient.SqlConnection;
import io.vertx.sqlclient.Tuple;

import java.util.ArrayList;

public class MySqlVerticle extends AbstractVerticle {

  // 第一步 声明router
  Router router;

  // 第一步 配置连接参数
  MySQLConnectOptions connectOptions = new MySQLConnectOptions()
    .setPort(3306)
    .setHost("192.168.31.80")
    .setDatabase("makelovetech")
    .setUser("root")
    .setPassword("123456");

  // 第二步 配置连接池 Pool options
  PoolOptions poolOptions = new PoolOptions()
    .setMaxSize(5);

  // 第三步 Create the client pool
  MySQLPool client ;

  @Override
  public void start(Future<Void> startFuture) throws Exception {

    client = MySQLPool.pool(vertx, connectOptions, poolOptions);

    // 第二步 初始化Router
    router = Router.router(vertx);

    // 第四步 配置Router解析url
    router.route("/").handler(req -> {
      req.response()
        .putHeader("content-type", "text/plain")
        .end("Hello from Vert.x!");
    });

    // 第四步 配置Router解析url
    router.route("/test/list").handler(req -> {

      Integer page;
      var temp = req.request().getParam("page");
      if (temp==null){
        page = 1;
      }else {
        page = Integer.valueOf(temp);
      }

      // Get a connection from the pool
      client.getConnection(ar1 -> {
        if (ar1.succeeded()) {
          System.out.println("Connected");
          // Obtain our connection
          SqlConnection conn = ar1.result();

          var offset = (page-1)*10;

          // All operations execute on the same connection
          conn
            .preparedQuery("SELECT id, name FROM test_find limit 10 offset ?")
            .execute(Tuple.of(offset), ar2 -> {
              // Release the connection to the pool
              conn.close();
              if (ar2.succeeded()) {
                var list = new ArrayList<JsonObject>();
                ar2.result().forEach(item->{
                  var json = new JsonObject();
                  json.put("id", item.getValue("id"));
                  json.put("name", item.getValue("name"));
                  list.add(json);
                });
                req.response()
                  .putHeader("content-type", "application/json")
                  .end(list.toString());
              } else {
                req.response()
                  .putHeader("content-type", "text/plain")
                  .end(ar2.cause().toString());
              }
            });
        } else {
          System.out.println("Could not connect: " + ar1.cause().getMessage());
        }
      });

    });


    // 第三步 将Router与vertx HttpServer 绑定
    vertx.createHttpServer().requestHandler(router).listen(8888, http -> {
      if (http.succeeded()) {
        startFuture.complete();
        System.out.println("HTTP server started on port 8888");
      } else {
        startFuture.fail(http.cause());
      }
    });
  }
}
